package com.jemaa.news.web;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.jemaa.news.app.Comment;
import com.jemaa.news.app.News;
import com.jemaa.news.app.NewsService;
import com.jemaa.news.app.Utils;
import com.jemaa.news.exceptions.JemaaException;
import com.jemaa.news.exceptions.SpecialCheckedApplicationError;

/**
 *
 * Controlleur Web pour l'administration du site. 
 *
 **/

@Controller
@RequestMapping("/admin/*")
@SessionAttributes("publishNews")
public class AdminController {

	private static final ResourceBundle pathBundle = ResourceBundle.getBundle("jdbc");
	
	private NewsService newsService;

	@Autowired
	public void setNewsService(NewsService newsService) {
		this.newsService = newsService;
	}
	
	
	/**
	 * Administration des news 
	 * 
	 */
	@RequestMapping(value = "index", method = RequestMethod.GET)
	public void index(News publishNews) {
	}
	
	
	@RequestMapping(value = "publish", method = RequestMethod.POST)
	public String publish(HttpServletRequest request,  News publishNews,
			BindingResult bindResult, Model model, 
			@RequestParam("imgFile") MultipartFile imgFile) throws Exception {
		
		if (StringUtils.isBlank(publishNews.getTitre())) {
			bindResult.rejectValue("titre", "required",
				"Saisissez un titre valide");
		}
		
		if (StringUtils.isBlank(publishNews.getAccroche())) {
			bindResult.rejectValue("accroche", "required",
				"Saisissez un titre valide");
		}
		
		if (StringUtils.isBlank(publishNews.getArticle())) {
			bindResult.rejectValue("article", "required",
				"Saisissez un titre valide");
		}
		
		if (bindResult.hasErrors()) {
			return "admin/index";
		} else {
			try {
				ServletContext sc = request.getSession().getServletContext();
				
				if (!imgFile.isEmpty() && !StringUtils.isBlank(publishNews.getImgUri())
						&& Utils.isValidExtension(publishNews.getImgUri())){
					//	create the file img of news
					byte[] bytes = imgFile.getBytes();
					String imgPath = sc.getRealPath("/static/images/");
					File img = new File(new File(imgPath), publishNews.getImgUri());
					FileOutputStream outImg = new FileOutputStream(img);
					outImg.write(bytes);
					outImg.close();
				}
					model.addAttribute("publishNews", publishNews);
				    return "admin/publish";
			} catch (IOException e) {
				throw new SpecialCheckedApplicationError(e.getMessage());
			}
		}
	}
	
	
	
	/**
	 * Validate the news and add the news with newsService
	 * 
	 * @param publishNews
	 * @param bindResult
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "valider", method = RequestMethod.GET)
	public String valider(HttpServletRequest request, @ModelAttribute("publishNews") News publishNews, News news) throws Exception {
			try {
				Long idNews = Calendar.getInstance().getTimeInMillis();
		        
		        //Publish the file accroche of news
		        String accPath = pathBundle.getString("static.accroches");  
		        File acc = new File(new File(accPath), idNews.toString());
				Writer outAcc = new BufferedWriter(new FileWriter(acc));
				outAcc.write(publishNews.getAccroche());
				outAcc.close();
		        
		        //Publish the file article of news
				
				String artPath = pathBundle.getString("static.articles");
		        File art = new File(new File(artPath), idNews.toString());
				Writer outArt = new BufferedWriter(new FileWriter(art));
				outArt.write(publishNews.getArticle());
				outArt.close();
				
		        //Add news in data base
				publishNews.setIdNews(idNews);
				publishNews.setIdImg(idNews);
				publishNews.setIdSrc(idNews);
				publishNews.setDateArt(new Date(idNews));
		        newsService.publish(publishNews);
		        
		        return "admin/index";
			} catch (IOException e) {
				throw new SpecialCheckedApplicationError(e.getMessage());
			}
			
	}
	
	
	@RequestMapping(value = "moderate", method = RequestMethod.GET)
	@ModelAttribute("comments")
	public List<Comment> moderate() throws Exception {
		try {
			return newsService.getNonModeratedComments();
		} catch (JemaaException e) {
			throw new SpecialCheckedApplicationError(e.getMessage());
		}
	}

	@RequestMapping(value = "accept", method = RequestMethod.GET)
	public String accept(@RequestParam("idComment") int idComment, Model model) throws Exception {
		try {
			newsService.acceptComment(idComment);
			List<Comment> comments = newsService.getNonModeratedComments();
			model.addAttribute("comments", comments);
			return "admin/moderate";
		} catch (JemaaException e) {
			throw new SpecialCheckedApplicationError(e.getMessage());
		}
	}
	
	@RequestMapping(value = "delete", method = RequestMethod.GET)
	public String delete(@RequestParam("idComment") int idComment, Model model) throws Exception {
		try {
			newsService.deleteComment(idComment);
			List<Comment> comments = newsService.getNonModeratedComments();
			model.addAttribute("comments", comments);
			return "admin/moderate";
		} catch (JemaaException e) {
			throw new SpecialCheckedApplicationError(e.getMessage());
		}
	}
	
}
